package com.mybatis.boost.generator.plugin;

import com.mybatis.boost.generator.plugin.adapter.MapperPluginAdapter;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.List;

/**
 * 将数据库中的时间日期映射为java8的时间日期
 *
 * @author jearton
 * @since 2016/12/8
 */
public class Jsr310Plugin extends MapperPluginAdapter {
    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        FullyQualifiedJavaType type = null;
        switch (JdbcType.forCode(introspectedColumn.getJdbcType())) {
            case DATE:
                type = new FullyQualifiedJavaType(LocalDate.class.getName());
                break;
            case TIME:
                type = new FullyQualifiedJavaType(LocalTime.class.getName());
                break;
            case TIMESTAMP:
                type = new FullyQualifiedJavaType(ZonedDateTime.class.getName());
                break;
            default:
                break;
        }
        if (type != null) {
            introspectedColumn.setFullyQualifiedJavaType(type);
            field.setType(type);
        }
        return true;
    }
}
